import abiao_utils from "abiao_utils";
import { Code } from "../enum/code.enum";
import Switch from "../models/common/switch.model";
import IntoServer from "../models/server/intoServer.model";
import Server from "../models/server/server.model";
import Result from "../utils/result";

/**
 * @Author: 陈瑞鹏
 * @Date:   2022-10-17 15:56:40
 * @Last Modified by:   陈瑞鹏
 * @Last Modified time: 2022-10-17 15:57:40
 */
export default class server {

  /**
   * 首服初始化
   */
  static async serverInit() {
    let ServerRes: any = await Server.findOne({});
    if (!ServerRes) {
      let info = {
        serverId: 1,
        serverName: '守卫战一服',
        createTime: abiao_utils.date(),
        isOpen: true,
      }
      await Server.create(info);

      await Switch.create({ name: 'server', isOpen: true });
    }
  }


  /**
   * 创建服务器
   * @param serverId 区服ID
   * @param serverName 区服名称
   */
  static async createServer(serverId: number, serverName: string): Promise<void> {
    let ServerRes: any = await Server.findOne({ serverId });
    if (!ServerRes) {
      let info = {
        serverId,
        serverName,
        createTime: abiao_utils.date(),
        isOpen: true
      }
      await Server.create(info);

    } else {
      throw new Result(Code.Fail, '服务器已存在!');
    }
  }


  /**
   * 记录进入服务器
   * @param serverId 服务器ID
   */
  static async record__into_server(openId: string, serverId: number): Promise<void> {
    let IntoServerRes: any = await IntoServer.findOne({ openId, serverId });
    if (!IntoServerRes) {
      let ServerRes: any = await Server.findOne({ serverId });
      let info = {
        openId,
        serverId,
        serverName: ServerRes.serverName,
        intoTime: abiao_utils.date()
      }
      await IntoServer.create(info);
    } else {
      await IntoServer.updateOne({ openId, serverId }, { intoTime: abiao_utils.date() });
    }
  }
}